package xyz.xtt.mybatis;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.model.ClassAnnotationAttributes;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import xyz.xtt.Application;

import java.io.File;
import java.nio.file.Paths;
import java.util.Collections;

/**
 * @author dale
 * @date 2025/2/8
 **/
@SpringBootTest(classes = Application.class)
@Slf4j
public class MybatisCodeGenerator {
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String jdbcUsername;
    @Value("${spring.datasource.password}")
    private String jdbcPassword;

    // 需要修改的配置 -- 开始

    /**
     * 作者
     */
    private static final String AUTHOR = "dale";
    /**
     * 需要生成的表,多个表名逗号分隔
     */
    private static final String TABLES = "tbl_user_fund_account,tbl_user_fund_record,tbl_business_order";

    // 需要修改的配置 -- 结束

    @Test
    public void generate() {
        // **2. 设置输出目录**
        String projectPath = Paths.get("").toAbsolutePath().toString();
        String outputDir = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java";
        String xmlOutputDir = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "mapper"; // ✅ 指定 XML 输出目录


        // **3. 代码生成**
        FastAutoGenerator.create(jdbcUrl, jdbcUsername, jdbcPassword)
                .dataSourceConfig(builder ->
                        builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            // 兼容旧版本转换成Integer
                            if (JdbcType.TINYINT == metaInfo.getJdbcType()) {
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);
                        })
                )
                .globalConfig(builder -> {
                    builder.author(AUTHOR)   // 作者
                            .outputDir(outputDir) // 代码输出目录
                            .disableOpenDir()   // 生成后不自动打开目录
                            .enableSwagger(); // 开启 swagger 模式
                })
                .packageConfig(builder ->
                        builder.parent("xyz.xtt.asset") // 包名
                                .entity("entity")
                                .mapper("mapper")
                                .service("service")
                                .serviceImpl("service.impl")
                                .xml("mapper")
                                .pathInfo(Collections.singletonMap(OutputFile.xml, xmlOutputDir)) // 指定 XML 输出目录
                )
                .strategyConfig(builder -> {
                    builder.addInclude(TABLES)  // 需要生成的表
                            .controllerBuilder().enableFileOverride().disable()// 关闭 Controller 生成
                            .entityBuilder()
                            .enableFileOverride()
                            .enableLombok(
                                    new ClassAnnotationAttributes("@Data", "lombok.Data"),
                                    new ClassAnnotationAttributes("@Builder", "lombok.Builder"),
                                    new ClassAnnotationAttributes("@EqualsAndHashCode(callSuper = false)", "lombok.EqualsAndHashCode"),
                                    new ClassAnnotationAttributes("@Accessors(chain = true)", "lombok.experimental.Accessors")
                            ).fieldUseJavaDoc(false)
                            .build() // 开启 entity 生成
                            .serviceBuilder().enableFileOverride().build() // 开启 service 生成
                            .mapperBuilder().enableFileOverride().build() // 开启 mapper 生成
                    ;
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用 FreeMarker 模板引擎
                .execute();
    }
}
